package cn.yuanqiao.quartz.task;

import cn.yuanqiao.archive.appManager.mapper.ArchiveMapper;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.quartz.util.FastjsonDateSerializer;
import cn.yuanqiao.quartz.util.MethodDescription;
import cn.yuanqiao.system.service.ISysConfigService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 同步电子阅览室
 */
@Component("syncDianZiYueLanShi")
public class SyncDianZiYueLanShi {
    private static final Logger log = LoggerFactory.getLogger(SyncDianZiYueLanShi.class);
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private ISysConfigService configService;

    @MethodDescription("发布到电子阅览室定时任务，arg0需要传入tenantCode")
    public void sendArchiveInfo(String tenantCode)
    {
        //String tables = configService.getConfigByKeyTenantCode("DZYLS_TABLES",tenantCode).getData();
        //if(StringUtils.isNotEmpty(tables)){
            //http://192.168.2.139:8082/hdda_yg/HddaYiTiAction?method=acceptTableData
            String path = configService.selectConfigByKeyTenantCode("DZYLS_PATH",tenantCode);
            if(StringUtils.isNotEmpty(path)){
                JSONObject object = new JSONObject();
                String tables = "SELECT ID,PARENT_ID,GROUP_ID as TEMPLATE_ID,NAME,CASE WHEN type = 0 then 'f' WHEN type = 1 then 'v' WHEN type = 3 then 'v' else 'f' end as TYPE,STORE_TYPE,STORE_MODE,CODE,REMARK," +
                        "FOLDER_TABLE_NAME as FOLDERTABLENAME,FILE_TABLE_NAME as FILETABLENAME,IS_DEL,CREATE_ID as CREATOR_ID,CREATE_BY as CREATOR,CREATE_TIME," +
                        "FONDS_CODE,FILE_TYPES FROM "+tenantCode+"_CATEGORY";
                List<Map<String, Object>> CATEGORY = archiveMapper.getTableInfo(tables);
                object.put("HDDACATEGORY",CATEGORY);

                tables = "SELECT ID, NAME, DESCRIPTION, creator_id as CREATOR, CREATE_TIME, IS_USE, TYPE,ORDER_NO FROM "+tenantCode+"_mdata_group";
                List<Map<String, Object>> MDATAGROUP = archiveMapper.getTableInfo(tables);
                object.put("HDDAMDATAGROUP",MDATAGROUP);

                tables = "SELECT ID, GROUP_ID, FIELD_CAPTION, FIELD_NAME, PROPERTY_NAME, FIELDTYPE, DATA_LENGTH, IS_INPUT, IS_UPDATE, IS_QUERY, IS_ARCHIVE_NO, " +
                        "IS_SYSTEM, IS_NO_EMPTY, DEFAULT_VALUE, IS_HIDDEN, REMARK, IS_EXPORT, EXPORT_COLUMN_NAME, EXPORT_ORDER_NO, CREATOR_ID, CREATE_TIME, COL_WIDTH," +
                        " TH_WIDTH, TH_ALIGN, TYPE, ORDER_NO, SHOWTYPE, IS_METADATA, BIANHAO, ENGLISH_NAME, DEFINITION, PURPOSE, CONSTRAINTS, repeat_string as REPEAT, " +
                        "ELEMENT_TYPE, DATA_TYPE, CODE, RANGE, DEFAULTVALUE, SOURCES, NOTES, MD_ORDER_NO, MD_LEVEL, IS_CATALOGUE, CATALOGUE_ORDER, IS_XMLTITLE, ZSFL," +
                        " CHECK_SPECIAL_CHARACTERS, CHECK_ARCHIVAL_CODE, CHECK_NOEMPTY, CHECK_CHONGFU, IS_IMPORT FROM "+tenantCode+"_mdata_list";
                List<Map<String, Object>> MDATALIST = archiveMapper.getTableInfo(tables);
                object.put("HDDAMDATALIST",MDATALIST);

                tables = "SELECT ID, PARENT_ID, NAME, TYPE, PROPERTY_NAME, PROPERTY_VALUE, CATEGORY_ID, FONDS_ID, ORDER_NO, REMARK, CREATOR," +
                        " CREATOR_ID, CREATE_TIME FROM "+tenantCode+"_trees";
                List<Map<String, Object>> HDDATREES = archiveMapper.getTableInfo(tables);
                object.put("HDDATREES",HDDATREES);

                tables = "SELECT ID, menu_id as ENTRY_ID, CATEGORY_ID, JIANLISTFIELD,JIANADDFIELD,JIANUPDATEFIELD,JIANEXPORTFIELD,JUANLISTFIELD,JUANADDFIELD," +
                        "JUANUPDATEFIELD,JUANEXPORTFIELD,JIANQUERY,JUANQUERY FROM "+tenantCode+"_apply";
                List<Map<String, Object>> HDDAAPPLY = archiveMapper.getTableInfo(tables);
                object.put("HDDAAPPLY",HDDAAPPLY);

                tables = "SELECT id as FONDS_ID, FONDS_CODE, FONDS_NAME,DEPT_ID, ORDER_NO FROM manage_fonds where TENANTCODE = '"+tenantCode+"'";
                List<Map<String, Object>> HDFONDS = archiveMapper.getTableInfo(tables);
                object.put("HDFONDS",HDFONDS);
                JSONObject jo = postJson2(path, object);
                log.info(jo.toJSONString());
            }else {
                throw new ServiceException("缺少系统参数：DZYLS_PATH");
            }
        //}else {
        //    throw new ServiceException("缺少系统参数：DZYLS_TABLES");
        //}

    }

    public JSONObject postJson2(String urlString ,JSONObject jsonObject) {
        JSONObject returnJson = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");//**注意点1**，需要此格式，后边这个字符集可以不设置
            connection.connect();
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());
            String info = JSONObject.toJSONString(jsonObject,new FastjsonDateSerializer());
            out.write(info.getBytes());//**注意点2**，需要此格式
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), StandardCharsets.UTF_8));//**注意点3**，需要此格式
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            System.out.println("POST JSON return:"+sb);
            returnJson = JSONObject.parseObject(sb.toString());
            reader.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnJson;
    }
}
